package io.renren.service.impl;

import io.renren.dao.SocialSecurityAreaBasicUpdateDao;
import io.renren.dao.SocialSecurityPayDetailDao;
import io.renren.dao.SocialSecurityPersonBasicDao;
import io.renren.entity.*;
import io.renren.entity.VO.SocialSecurityAreaBasicEntityVO;
import io.renren.service.SocialSecurityPayDetailService;
import io.renren.utils.ReflectUtil;
import io.renren.utils.SocialSecurityAreaBasicUtils;
import io.renren.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.*;

import io.renren.dao.SocialSecurityAreaBasicDao;
import io.renren.service.SocialSecurityAreaBasicService;
import org.springframework.transaction.annotation.Transactional;


@Service("socialSecurityAreaBasicService")
public class SocialSecurityAreaBasicServiceImpl implements SocialSecurityAreaBasicService {
    @Autowired
    private SocialSecurityAreaBasicDao socialSecurityAreaBasicDao;
    @Autowired
    private SocialSecurityAreaBasicUpdateDao socialSecurityAreaBasicUpdateDao;
    @Autowired
    private SocialSecurityPersonBasicDao socialSecurityPersonBasicDao;
    @Autowired
    private SocialSecurityPayDetailDao socialSecurityPayDetailDao;

    @Override
    public SocialSecurityAreaBasicEntity queryObject(Integer id) {
        return socialSecurityAreaBasicDao.queryObject(id);
    }

    @Override
    public List<SocialSecurityAreaBasicEntityVO> queryList(Map<String, Object> map) {
        return socialSecurityAreaBasicDao.queryVOList(map);
        //return socialSecurityAreaBasicDao.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return socialSecurityAreaBasicDao.queryTotal(map);
    }

    @Override
    public String save(SocialSecurityAreaBasicEntity socialSecurityAreaBasic) {
        String seachCode = socialSecurityAreaBasic.getProvince() + socialSecurityAreaBasic.getCity() + socialSecurityAreaBasic.getDistrict();
        List<SocialSecurityAreaBasicEntity> list = socialSecurityAreaBasicDao.queryByDistrict(seachCode);
        if (list != null && list.size() > 0) {
            return "不能新增已存在的区域";
        } else {
            int index = 0;
            try {
                index = socialSecurityAreaBasicDao.querySumIndex();
            } catch (Exception e) {
                e.printStackTrace();
            }
            socialSecurityAreaBasic.setIndex(index + 1);
            Calendar ca = Calendar.getInstance();
            int year = ca.get(Calendar.YEAR);
            int month = ca.get(Calendar.MONTH)+1;
            String smonth = socialSecurityAreaBasic.getMonth();
            String syear = socialSecurityAreaBasic.getYear();
            if(!StringUtils.isBlank(smonth)){
                month = Integer.valueOf(smonth);
            }
            if(StringUtils.isNotBlank(syear)){
                year = Integer.valueOf(syear);
            }
            Class areaBasic = socialSecurityAreaBasic.getClass();
            Field[] fs = areaBasic.getDeclaredFields();
            for (Field f : fs) {
                f.setAccessible(true);
                String name = f.getName();
                if (f.getGenericType().toString().equals("class java.lang.Double")) {
                    Object val = null;
                    try {
                        val = f.get(socialSecurityAreaBasic);
                        if(val==null){
                            f.set(socialSecurityAreaBasic,0d);
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
            if(StringUtils.isBlank(socialSecurityAreaBasic.getIstotal())){
                socialSecurityAreaBasic.setIstotal("0");
            }
            if(StringUtils.isBlank(socialSecurityAreaBasic.getStatus())){
                socialSecurityAreaBasic.setStatus("0");
            }
            for(int i = month; i<=12; i++){
                socialSecurityAreaBasic.setYear(year+"");
                socialSecurityAreaBasic.setMonth(i+"");
                socialSecurityAreaBasicDao.save(socialSecurityAreaBasic);
            }
           return null;
        }
    }

    @Override
    @Transactional
    public void update(SocialSecurityAreaBasicEntity socialSecurityAreaBasic) {
        //把每种保险的详细信息列出来
        double yanglbasic = socialSecurityAreaBasic.getYanglbxBasic()==null?0:socialSecurityAreaBasic.getYanglbxBasic();
        double yangldwbl = socialSecurityAreaBasic.getYanglbxDwbl()==null?0:socialSecurityAreaBasic.getYanglbxDwbl();
        double yanglgrbl = socialSecurityAreaBasic.getYanglbxGrbl()==null?0:socialSecurityAreaBasic.getYanglbxGrbl();
        double yilbasic = socialSecurityAreaBasic.getYilbxBasic()==null?0:socialSecurityAreaBasic.getYilbxBasic();
        double yildwbl = socialSecurityAreaBasic.getYilbxDwbl()==null?0:socialSecurityAreaBasic.getYilbxDwbl();
        double yilgrbl = socialSecurityAreaBasic.getYilbxGrbl()==null?0:socialSecurityAreaBasic.getYilbxGrbl();
        double shiybasic = socialSecurityAreaBasic.getShiybxBasic()==null?0:socialSecurityAreaBasic.getShiybxBasic();
        double shiydwbl = socialSecurityAreaBasic.getShiybxDwbl()==null?0:socialSecurityAreaBasic.getShiybxDwbl();
        double shiygrbl = socialSecurityAreaBasic.getShiybxGrbl()==null?0:socialSecurityAreaBasic.getShiybxGrbl();
        double gongsbasic = socialSecurityAreaBasic.getGongsbxBasic()==null?0:socialSecurityAreaBasic.getGongsbxBasic();
        double gongsdwbl = socialSecurityAreaBasic.getGongsbxDwbl()==null?0:socialSecurityAreaBasic.getGongsbxDwbl();
        double gongsgrbl = socialSecurityAreaBasic.getGongsbxGrbl()==null?0:socialSecurityAreaBasic.getGongsbxGrbl();
        double shengybasic = socialSecurityAreaBasic.getShengybxBasic()==null?0:socialSecurityAreaBasic.getShengybxBasic();
        double shengydwbl = socialSecurityAreaBasic.getShengybxDwbl()==null?0:socialSecurityAreaBasic.getShengybxDwbl();
        double shengygrbl = socialSecurityAreaBasic.getShengybxGrbl()==null?0:socialSecurityAreaBasic.getShengybxGrbl();
        double totalbasic = socialSecurityAreaBasic.getTotalBasic()==null?0:socialSecurityAreaBasic.getTotalBasic();
        double totaldwbl = socialSecurityAreaBasic.getTotalDwbl()==null?0:socialSecurityAreaBasic.getTotalDwbl();
        double totalgrbl = socialSecurityAreaBasic.getTotalGrbl()==null?0:socialSecurityAreaBasic.getTotalGrbl();

        Calendar ca = Calendar.getInstance();
        int curyear = ca.get(Calendar.YEAR);
        int year = Integer.valueOf(socialSecurityAreaBasic.getYear());
        int month = Integer.valueOf(socialSecurityAreaBasic.getMonth());

        int index = socialSecurityAreaBasic.getIndex();

        int id = socialSecurityAreaBasic.getId();
        SocialSecurityAreaBasicEntity basicen = socialSecurityAreaBasicDao.queryObject(id);
        SocialSecurityAreaBasicUpdateEntity pojo = reflectCopy(basicen, socialSecurityAreaBasic);
        System.out.print("basicen" + basicen.getYanglbxBasic() + "socialSecurityAreaBasic:" + socialSecurityAreaBasic.getYanglbxBasic());
        pojo.setBasicId(id);

        Map<String, Object> params = new HashMap<>();
        params.put("province",socialSecurityAreaBasic.getProvince());
        params.put("city",socialSecurityAreaBasic.getCity());
        params.put("district",socialSecurityAreaBasic.getDistrict());
        for (int i = year; i <= curyear; i++) {
            if (i == year) {
                for (int j = month; j <= 12; j++) {
                    params.put("year",i);
                    params.put("month",j);
                    SocialSecurityAreaBasicEntity ab = socialSecurityAreaBasicDao.getAreaBasicByParams(params);
                    ab = (SocialSecurityAreaBasicEntity)ReflectUtil.reflectClass(socialSecurityAreaBasic,ab);//reflectSSAreaBasic(socialSecurityAreaBasic,ab);
                    socialSecurityAreaBasicDao.update(ab);
                }
            } else {
                for (int j = 1; j <= 12; j++) {
                    params.put("year",i);
                    params.put("month",j);
                    SocialSecurityAreaBasicEntity ab = socialSecurityAreaBasicDao.getAreaBasicByParams(params);
                    ab = (SocialSecurityAreaBasicEntity)ReflectUtil.reflectClass(socialSecurityAreaBasic,ab);
                    //ab = reflectSSAreaBasic(socialSecurityAreaBasic,ab);
                    socialSecurityAreaBasicDao.update(ab);
                }
            }
        }

        //根据结算点绑定的区域基数表区域字段(index)来获取所有挂靠在该区域下的结算点记录
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("year", year);
        map.put("month", month);
        List<CustomSettlementEntity> settlementList = socialSecurityAreaBasicDao.getCustomSettlementByIndex(index);
        for (CustomSettlementEntity settlementEntity : settlementList) {
            SocialSecurityPersonBasicEntity basic = new SocialSecurityPersonBasicEntity();
            //根据结算点编号获取该结算点下所有的人员社保基数记录
            String settlementid = settlementEntity.getId();
            /**
             * 标记该结算点社保核算标准是按照区域社保基数(0)还是按照个人社保基数(1)
             * 如果核算标准按区域社保基数，则个人社保基数完全依据区域社保基数表来修改
             * 如果核算标准按人员社保基数，则个人社保基数表的缴费基数字段不修改，只修改缴费比例
             */
            String empbasenum = settlementEntity.getEmpBaseNum();
            map.put("settlementid", settlementid);
            List<SocialSecurityPersonBasicEntity> sspersonBasicList = socialSecurityPersonBasicDao.getSSPersonBasicInfo(map);
            for (SocialSecurityPersonBasicEntity socialSecurityPersonBasicEntity : sspersonBasicList) {
                SocialSecurityPersonBasicEntity ssperson = ReflectUtil.setSSPersonBasic(socialSecurityAreaBasic, socialSecurityPersonBasicEntity, empbasenum);
                socialSecurityPersonBasicDao.update(ssperson);
            }


            //根据结算点编号获取所有结算点字段值为该结算点编号的社保缴付明细表记录
            List<SocialSecurityPayDetailEntity> payDetailList = socialSecurityPayDetailDao.getPayDetailBySettlementid(map);
            for (SocialSecurityPayDetailEntity payDetail : payDetailList) {
                /**
                 * 如果是已经有付款记录的社保明细记录，即表明该记录为已经结算过的记录，
                 * 就修改补差字段的数据，同时修改补差缴付状态为未缴付
                 */
                SocialSecurityAreaBasicUtils.updatePayDetail(payDetail, yanglbasic, yangldwbl, yanglgrbl,
                        shengybasic, shengydwbl, shengygrbl, gongsbasic, gongsdwbl, gongsgrbl,
                        yilbasic, yildwbl, yilgrbl, shiybasic, shiydwbl, shiygrbl,
                        totalbasic, totaldwbl, totalgrbl, empbasenum);
                socialSecurityPayDetailDao.update(payDetail);

            }
        }
        socialSecurityAreaBasicUpdateDao.save(pojo);
    }


    @Override
    public void delete(Integer id) {
        socialSecurityAreaBasicDao.delete(id);
    }

    @Override
    public void deleteBatch(Integer[] ids) {
        socialSecurityAreaBasicDao.deleteBatch(ids);
    }


    public SocialSecurityAreaBasicUpdateEntity reflectCopy(SocialSecurityAreaBasicEntity basicen, SocialSecurityAreaBasicEntity nPojo) {
        SocialSecurityAreaBasicUpdateEntity update = new SocialSecurityAreaBasicUpdateEntity();
        Class updateClass = update.getClass();
        Field[] fs = updateClass.getDeclaredFields();
        Class basicClass = basicen.getClass();
        Field[] fields = basicClass.getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);
            String name = field.getName();

            Object val = null;
            try {
                val = field.get(basicen);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

            for (Field f : fs) {
                f.setAccessible(true);
                String uname = f.getName();
                if (!uname.equals("serialVersionUID")) {
                    if (uname.equals(name)) {
                        try {
                            f.set(update, val);
                            break;
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        }

        Class basicClassNew = nPojo.getClass();
        Field[] fieldsNew = basicClassNew.getDeclaredFields();
        for (Field field : fieldsNew) {
            field.setAccessible(true);
            String name = field.getName();
            Object val = null;
            try {
                val = field.get(nPojo);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        /*	Class updateClass = update.getClass();
			Field[] fs = updateClass.getDeclaredFields();*/
            for (Field f : fs) {
                f.setAccessible(true);
                String uname = f.getName();
                if (!uname.equals("serialVersionUID")) {
                    if (uname.equals(name + "New")) {
                        try {
                            f.set(update, val);
                            break;
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        }


        return update;
    }


    @Override
    public List<SocialSecurityAreaBasicEntity> queryByIndex(Map<String, Object> map) {
        List<SocialSecurityAreaBasicEntity> list = socialSecurityAreaBasicDao.queryByIndex(map);
        return list;

    }

    @Override
    public List<Map<String, Object>> getListinfo(Map<String, Object> map) {
        return socialSecurityAreaBasicDao.getListinfo(map);
    }


}
